﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DNA.Models;
using System.Web.Security;
using System.Xml;
using System.IO;

namespace DNA.Controllers
{ 
    public class UserController : Controller
    {
        private DNAAnalysisEntities db = new DNAAnalysisEntities();

        //
        // GET: /User/

        public ViewResult Index()
        {            
            //var user = db.User.Include("Perfil").Include("DNA");
            //if(HttpContext.Request.UrlReferrer.ToString().Contains("Create"))
            //{
            //    ViewBag.Greeting = Utils.Utilities.getTime();
            //    return View("../Home/Index");
            //}
            //else
            //{
            //    int userId = 0;
            //    try
            //    {
            //        userId = int.Parse(Session["UserId"].ToString());
            //    }
            //    catch (Exception ex)
            //    {
            //        return View("LogOn");
            //    }
            //    if(db.User.First(user => user.Id == userId).Id == 1)
            //    {
            //        return View(db.User.ToList());
            //    }
            //    else
            //    {
            //        return View(db.User.First(user => user.Id == userId));
            //    }
            //}
            return View(db.User.ToList());
        }

        //
        // GET: /User/Details/5

        public ViewResult Details(int id)
        {
            User user = db.User.Single(u => u.Id == id);
            return View(user);
        }

        //
        // GET: /User/Create

        public ActionResult Create()
        {
            ViewBag.Perfil_Id = new SelectList(db.Perfil, "Id", "Name");
            ViewBag.Id = new SelectList(db.DNA, "Id", "CompleteDNASequence");
            return View();
        } 

        //
        // POST: /User/Create

        [HttpPost]
        public ActionResult Create(User user)
        {
            
            if (ModelState.IsValid)
            {
                if(user.Password == user.PasswordConfirmation)
                {
                    user.Perfil_Id = 1; //Defini o usuário com perfil de usuario final
                    db.User.AddObject(user);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
  

            ViewBag.Perfil_Id = new SelectList(db.Perfil, "Id", "Name", user.Perfil_Id);
            ViewBag.Id = new SelectList(db.DNA, "Id", "CompleteDNASequence", user.Id);
            return View(user);
        }
        
        //
        // GET: /User/Edit/5
 
        public ActionResult Edit(int id)
        {
            User user = db.User.Single(u => u.Id == id);
            ViewBag.Perfil_Id = new SelectList(db.Perfil, "Id", "Name", user.Perfil_Id);
            ViewBag.Id = new SelectList(db.DNA, "Id", "CompleteDNASequence", user.Id);
            return View(user);
        }

        //
        // POST: /User/Edit/5

        [HttpPost]
        public ActionResult Edit(User user)
        {
            if (ModelState.IsValid)
            {
                db.User.Attach(user);
                db.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.Perfil_Id = new SelectList(db.Perfil, "Id", "Name", user.Perfil_Id);
            ViewBag.Id = new SelectList(db.DNA, "Id", "CompleteDNASequence", user.Id);
            return View(user);
        }

        //
        // GET: /User/Delete/5
 
        public ActionResult Delete(int id)
        {
            User user = db.User.Single(u => u.Id == id);
            return View(user);
        }

        //
        // POST: /User/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {            
            User user = db.User.Single(u => u.Id == id);
            db.User.DeleteObject(user);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            Session["LogonDate"] = "";
            return RedirectToAction("Index", "Home");
        }

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(User model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (VerificaPassword(model.Email, model.Password))
                {
                    User user = db.User.Single(u => u.Email == model.Email);
                    
                    FormsAuthentication.SetAuthCookie(user.Email,true);
                    Session["LogonDate"] = DateTime.Now.ToString();
                    Session["UserId"] = user.Id.ToString();
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Usuário ou senha incorreto.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        private bool VerificaPassword(string email, string password)
        {
            try
            {
                User user = db.User.First(u => u.Email == email);
                if (user.Password.Equals(password))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                return false;
            }
        }

        [HttpPost]
        public ActionResult Importar(User user)
        {
            //Caminho do arquivo xml
            string arquivo = "";

            //Prepara a leitura do arquivo
            foreach (string fileName in Request.Files)
            {
                HttpPostedFileBase postedFile = Request.Files[fileName];

                postedFile.SaveAs(Server.MapPath("~/XMLs/") + Path.GetFileName(postedFile.FileName));

                arquivo = Server.MapPath("~/XMLs/") + Path.GetFileName(postedFile.FileName);
            }

            //Cria uma variavel do tipo xml
            XmlDocument xmlDoc = new XmlDocument();

            //Carrega o arquivo xml
            xmlDoc.Load(arquivo);


            //Percorre todos os nós do arquivo xml
            for (int i = 0; i < xmlDoc.DocumentElement.ChildNodes.Count; i++)
            {
                XmlNode root = xmlDoc.DocumentElement.ChildNodes[i];
                User usr = new User();
                //Pega dados do usuario do xml
                string nome = "";
                string sobrenome = "";
                string email = "";
                string adm = "";
                string pesquisador = "";
                try
                {
                    nome = root.SelectSingleNode("name").ChildNodes[0].Value;
                }
                catch(Exception ex)
                {
                    ex.Message.ToString(); 
                }
                try
                {
                    sobrenome = root.SelectSingleNode("surname").ChildNodes[0].Value;
                }
                catch (Exception ex)
                {
                    ex.Message.ToString();
                }
                try
                {
                    email = root.SelectSingleNode("email").ChildNodes[0].Value;
                }
                catch (Exception ex)
                {
                    ex.Message.ToString();
                }
                try
                {
                    adm = root.SelectSingleNode("administrator").ChildNodes[0].Value;
                }
                catch (Exception ex)
                {
                    ex.Message.ToString();
                }
                try
                {
                    pesquisador = root.SelectSingleNode("researcher").ChildNodes[0].Value;
                }
                catch (Exception ex)
                {
                    ex.Message.ToString();
                }

                usr.Name = verificaVazio(nome);
                usr.Lastname = verificaVazio(sobrenome);
                usr.Email = verificaVazio(email);
                usr.Perfil_Id = verificaPerfil(adm, pesquisador);
                usr.PasswordConfirmation = nome;
                usr.Password = nome;
                db.User.AddObject(usr);
                db.SaveChanges();
            }

            return RedirectToAction("Index"); 
        }

        private string verificaVazio(string dado)
        {
            if (dado.Trim().Equals(""))
            {
                return "N/A";
            }
            else
            {
                return dado;
            }

        }

        private int verificaPerfil(string adm, string pesquisador)
        {
            if (adm.Equals("true"))
            {
                return 3;
            }
            else if (pesquisador.Equals("true"))
            {
                return 2;
            }
            else
            {
                return 1;
            }
        }
    }
}